package com.sc.VenusQueryBeta.ui.fragments.account.zhuanma;

import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dou361.dialogui.DialogUIUtils;
import com.dou361.dialogui.listener.DialogUIDateTimeSaveListener;
import com.dou361.dialogui.widget.DateSelectorWheelView;
import com.example.zhouwei.library.CustomPopWindow;
import com.hengjun.kingstar.sdk.base.BasePresenter;
import com.hengjun.kingstar.sdk.base.fragment.BaseMVPCompatFragment;
import com.hengjun.kingstar.sdk.utils.LogUtils;
import com.hengjun.kingstar.sdk.utils.SpUtils;
import com.hengjun.kingstar.sdk.utils.ToastUtils;
import com.sc.VenusQueryBeta.R;
import com.sc.VenusQueryBeta.adapter.PopAdapter;
import com.sc.VenusQueryBeta.adapter.VipUserInfornationAdapter;
import com.sc.VenusQueryBeta.constant.Constants;
import com.sc.VenusQueryBeta.contract.account.zhuanma.ZhuanMaContract;
import com.sc.VenusQueryBeta.global.MyApplication;
import com.sc.VenusQueryBeta.model.bean.account.AccountList;
import com.sc.VenusQueryBeta.model.bean.account.CurrencyListBean;
import com.sc.VenusQueryBeta.model.bean.account.MaxChangemonthBean;
import com.sc.VenusQueryBeta.model.bean.login.QueryRegisBean;
import com.sc.VenusQueryBeta.model.bean.login.UsersLoginBean;
import com.sc.VenusQueryBeta.presenter.account.zhuanma.ZhuanMaPresenter;

import java.util.Calendar;

import butterknife.BindView;
import butterknife.OnClick;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.header.MaterialHeader;

import static android.view.Gravity.CENTER;

/**
 * 轉碼activity
 */
public class ZhuanMaFragment extends BaseMVPCompatFragment<ZhuanMaContract.ZhuanMaPresenter> implements ZhuanMaContract.IZhuanMaView {
    private static ZhuanMaFragment fragment;
    @BindView(R.id.ibtn_zhuanma_back)
    ImageButton ibtnZhuanmaBack;
    @BindView(R.id.vip_user)
    TextView vipUser;
    @BindView(R.id.vip_uservip_user_infornation)
    RecyclerView vipUservipUserInfornation;
    @BindView(R.id.ptr_class)
    PtrClassicFrameLayout ptrClass;
    @BindView(R.id.visible)
    TextView visible;
    @BindView(R.id.total_money)
    TextView totalMoney;
    @BindView(R.id.tv_currency_type)
    TextView tvCurrencyType;
    @BindView(R.id.chooise_company)
    TextView chooiseCompany;
    @BindView(R.id.chooise_time)
    TextView chooiseTime;
    private CustomPopWindow mCustomPopWindow;
    private VipUserInfornationAdapter vipServiceAdapter;
    private VipUserInfornationAdapter vipUserInfornationAdapter;
    private CustomPopWindow mClubPopWindow;
    private PopAdapter popAdapter;
    private String time1;
    private String time2;
    private QueryRegisBean queryRegisBean;
    private int clientindex;
    private int roomId;
    private String roomyear;
    private String roommonth;
    private CurrencyListBean mallRoomListBean;//所有币种
    private MaxChangemonthBean mmaxChangemonthBean;
    private boolean isCend = false;
    private RecyclerView clubrecyclerView;
    private UsersLoginBean loginBean;
    private PopupWindow popupWindow;
    private String s;
    private int type = 0;
    private String currency;
    private String currencyname;


    public static ZhuanMaFragment newInstance(QueryRegisBean queryRegisBean, int clientindex, String currency_type) {
        Bundle args = new Bundle();
        args.putInt(Constants.CLIENTINDEX, clientindex);
        args.putSerializable(Constants.QUERY_SETTING, queryRegisBean);
        args.putString(Constants.CURRENCY_TYPE, currency_type);
//        args.putString(Constants.CLIENTID, clientId);
//        args.putString(Constants.YEAR,roomyear);
//        args.putString(Constants.MONTH,roommonth);
//        args.putInt(Constants.ROOMID,roomId);
//        args.putString(Constants.ROOMNAME, roomname);
        fragment = new ZhuanMaFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public boolean onBackPressedSupport() {
        pop();
        return true;
    }

    /**
     * 初始化头部
     */
//    private void initHeadView() {
//        if (headView == null) {
//            headView = ResourcesUtils.inflate(R.layout.rv_top);
//        }
//        if (errorView == null) {
//            errorView = ResourcesUtils.inflate(R.layout.view_network_error);
//        }
//        errorView.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                mPresenter.queryClientReserved02(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().getServerProject(), queryRegisBean.getServerSetting().getServerPort(),
//                        clientindex, roomyear + "", roommonth + "", "0", "0");
//            }
//        });
//        //獲取
//        btn_chooise_currency = headView.findViewById(R.id.tv_currency_type);
//        btn_choose_club = headView.findViewById(R.id.chooise_company);
//        btn_choose_club.setText(currency);
//        total_money = headView.findViewById(R.id.total_money);
//        btn_choose_time = headView.findViewById(R.id.chooise_time);
//        btn_choose_time.setText(roomyear + "/" + roommonth);//设置日期
//        btn_chooise_currency.setText(currency);
//    }
    @Override
    public int getLayoutId() {
        return R.layout.activity_zhuan_ma;
    }

    /**
     * 转码信息
     *
     * @param savedInstanceState savedInstanceState
     */
    @Override
    public void initUI(View view, @Nullable Bundle savedInstanceState) {
        chooiseCompany.setText(currency);
        tvCurrencyType.setText(currency);

        //初始化一个空list的adapter，网络错误时使用，第一次加载到数据时重新初始化adapter并绑定recycleview
        vipUserInfornationAdapter = new VipUserInfornationAdapter(R.layout.item_zhuanma);
        vipUservipUserInfornation.setAdapter(vipUserInfornationAdapter);
        vipUservipUserInfornation.setLayoutManager(new LinearLayoutManager(mActivity));
        Calendar c = Calendar.getInstance();//
        roomyear = String.valueOf(c.get(Calendar.YEAR)); // 获取当前年份
        roommonth = String.valueOf(c.get(Calendar.MONTH) + 1);// 获取当前月份
//        initHeadView();//初始化头部布局
        chooiseTime.setText(roomyear + "/" + roommonth);
        initClub();//初始化集團佈局
    }

    @NonNull
    @Override
    public BasePresenter initPresenter() {
        return ZhuanMaPresenter.newInstance();
    }

    /**
     * 选择集团小窗口
     */
    private void initClub() {
        View contentView = LayoutInflater.from(mActivity).inflate(R.layout.pop_list, null);
        //创建并显示popWindow
//        mClubPopWindow1 = new PopupWindow(mActivity);

        mClubPopWindow = new CustomPopWindow.PopupWindowBuilder(mActivity)
                .setView(contentView).setOnDissmissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        WindowManager.LayoutParams lp = mActivity.getWindow().getAttributes();
                        lp.alpha = 1f;
                        mActivity.getWindow().setAttributes(lp);
                    }
                })
                .create();
        clubrecyclerView = contentView.findViewById(R.id.recyclerView);
    }

    @OnClick({R.id.ibtn_zhuanma_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ibtn_zhuanma_back:
                pop();
                break;
        }
    }


    /**
     * 下拉刷新監聽
     */
    private void reFreshListener() {
        MaterialHeader header = new MaterialHeader(mContext);
        ptrClass.addPtrUIHandler(header);
        ptrClass.setLastUpdateTimeRelateObject(this);//设置刷新支持时间
        ptrClass.setResistance(1.7f);//设置下拉的阻尼系数，值越大感觉越难下拉
        ptrClass.setDurationToCloseHeader(1000);//设置刷新完成，头部回弹时间，注意和前一个进行区别
        ptrClass.setPullToRefresh(false);//设置下拉过程中执行刷新，我们一般设置为false
        ptrClass.setKeepHeaderWhenRefresh(true);//设置刷新的时候是否保持头部
        ptrClass.setPtrHandler(new PtrDefaultHandler() {               //下拉刷新
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                //模拟联网，延迟更新数据
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
//                      mAdapterWithHF.notifyDataSetChanged();//适配器更新数据
                        if (ptrClass != null && mPresenter != null) {
                            if (queryRegisBean != null && !queryRegisBean.getServerSetting().getServerAddress().equals("")) {
//                            vipUserInfornationAdapter.removeAllHeaderView();//必須先remove headview
                                //查询子户口
                                LogUtils.e("month123=" + roommonth + "year123=" + roomyear);
                                showProgressDialog("请稍等...");
                                if (roommonth.equals("全年")) {
                                    mPresenter.queryClientReserved02(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().getServerProject(), queryRegisBean.getServerSetting().getServerPort(),
                                            clientindex, roomyear + "", "", "0", "0", chooiseCompany.getText().toString());
                                } else {
                                    mPresenter.queryClientReserved02(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().getServerProject(), queryRegisBean.getServerSetting().getServerPort(),
                                            clientindex, roomyear + "", roommonth + "", "0", "0", chooiseCompany.getText().toString());
                                }
                            } else {
                                hideProgressDialog();
                            }
                        }else {
                            hideProgressDialog();
                        }
                    }
                }, 1000);
            }
        });
    }

    /**
     * 时间选择
     */
    private void chooisTime() {
        DialogUIUtils.showDatePick(mActivity, CENTER, "选择日期", System.currentTimeMillis() + 60000, DateSelectorWheelView.TYPE_YYYYMM, 0, new DialogUIDateTimeSaveListener() {
            @Override
            public void onSaveSelectedDate(int tag, String selectedDate) {//点击年月监听器
                isCend = true;
                time1 = selectedDate;
                roomyear = selectedDate.substring(0, 4);
                roommonth = selectedDate.substring(selectedDate.length() - 2, selectedDate.length());
                time2 = time1.replace("-", "/");
                chooiseTime.setText(time2);
                //查询子户口//查询子户口//查询子户口//查询子户口//查询子户口//查询子户口//查询子户口
                if (roommonth.equals("全年")) {
                    showProgressDialog("请稍等...");
                    mPresenter.queryClientReserved02(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().getServerProject(), queryRegisBean.getServerSetting().getServerPort(),
                            clientindex, roomyear + "", "", " 0", "0",chooiseCompany.getText().toString());
                } else {
                    showProgressDialog("请稍等...");
                    mPresenter.queryClientReserved02(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().getServerProject(), queryRegisBean.getServerSetting().getServerPort(),
                            clientindex, roomyear + "", roommonth + "", "0", "0",chooiseCompany.getText().toString());
                }
            }

        }).show();
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        if (queryRegisBean != null && !queryRegisBean.getServerSetting().getServerAddress().equals("")) {
            //查询所有厅
            mPresenter.queryCurrencyList(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().getServerProject(), queryRegisBean.getServerSetting().getServerPort());
        } else {
            ToastUtils.showToast("数据异常");
        }
    }

    /**
     * 初始化数据
     */
    @Override
    public void initData() {
        super.initData();
        loginBean = SpUtils.getObject(MyApplication.app, UsersLoginBean.class);
        if (fragment.getArguments() != null) {
            queryRegisBean = (QueryRegisBean) fragment.getArguments().getSerializable(Constants.QUERY_SETTING);
            clientindex = fragment.getArguments().getInt(Constants.CLIENTINDEX, 0);
            currency = fragment.getArguments().getString(Constants.CURRENCY_TYPE, "");
//            clientId = fragment.getArguments().getString(Constants.CLIENTID, "");
        }
    }

    /**
     * 填充户口适配器
     *
     * @param accountListBean
     */
    private void initRvList(final AccountList accountListBean) {
        vipUserInfornationAdapter = new VipUserInfornationAdapter(R.layout.item_zhuanma, accountListBean.getClients());
        vipUserInfornationAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {//監聽item 劍點擊
                LogUtils.e("room=====================" + currencyname);
                start(ZhuanMa01Fragment.newInstance(queryRegisBean, Integer.parseInt(accountListBean.getClients().get(position).getClientindex()), roomyear, roommonth, roomId, type, chooiseCompany.getText().toString()));
            }
        });
        vipUservipUserInfornation.setAdapter(vipUserInfornationAdapter);
        reFreshListener();//rv下拉刷新
        ptrClass.refreshComplete();//

    }

    @Override
    public void showNetworkError(Throwable throwable) {
        ptrClass.refreshComplete();//
        hideProgressDialog();
    }

    /**
     * 查詢廳成功回調
     *
     * @param allRoomListBean
     */
//    @Override
//    public void showqueryAllRoomList(final AllRoomListBean allRoomListBean) {
//        if (allRoomListBean != null && allRoomListBean.getRoomList().size() > 0) {
//            roomId = Integer.parseInt(allRoomListBean.getRoomList().get(0).getRoomid());
//            //填充廳數據
//            //初始化一个空list的adapter，网络错误时使用，第一次加载到数据时重新初始化adapter并绑定recycleview
//            popAdapter = new PopAdapter(R.layout.pop_list_item, allRoomListBean.getRoomList());
//            clubrecyclerView.setAdapter(popAdapter);
//            clubrecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
//            //集團點擊監聽
//            popAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
//                @Override
//                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                    roomId = Integer.parseInt(allRoomListBean.getRoomList().get(position).getRoomid());
//                    btn_choose_club.setText(allRoomListBean.getRoomList().get(position).getRoomname());//動態改變集團名稱
//                    roomname = allRoomListBean.getRoomList().get(position).getRoomname();
//                    //查詢最大日期
//                    if (position != 0) {
//                        mPresenter.queryMaxChangemonth(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().getServerProject(), queryRegisBean.getServerSetting().getServerPort(), roomId);
//                    } else {
//                        if (roommonth.equals("全年")) {
//                            mPresenter.queryClientReserved02(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().getServerProject(), queryRegisBean.getServerSetting().getServerPort(),
//                                    clientindex, roomId, roomyear + "", "", "0", "0", type);
//                        } else {
//                            mPresenter.queryClientReserved02(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().getServerProject(), queryRegisBean.getServerSetting().getServerPort(),
//                                    clientindex, roomId, roomyear + "", roommonth + "", "0", "0", type);
//                        }
//                    }
//
//                    mClubPopWindow.dissmiss();
//                }
//            });
//            //填充廳數據
//
//            mallRoomListBean = allRoomListBean;
////            roomId = allRoomListBean.getRoomList().get(0).getRoomid();//默认第一个厅
////            //查询子户口
//            if (queryRegisBean != null && !queryRegisBean.getServerSetting().getServerAddress().equals("")) {
//                //查询子户口
//                showProgressDialog("请稍等...");
//                mPresenter.queryClientReserved02(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().getServerProject(), queryRegisBean.getServerSetting().getServerPort(),
//                        clientindex, roomId, roomyear + "", roommonth + "", "0", "0", type);
//            }
//        }
//    }

    /**
     * 子户口查询成功回调
     *
     * @param accountListBean accountListBean
     */
    @Override
    public void showZiHuKouList(AccountList accountListBean) {
        vipUserInfornationAdapter.removeAllHeaderView();
        if (ptrClass != null && visible != null) {
            if (accountListBean != null && accountListBean.getClients() != null && accountListBean.getClients().size() > 0) {//有数据

                ptrClass.setVisibility(View.VISIBLE);
                visible.setVisibility(View.GONE);
                initRvList(accountListBean);
            } else {
                visible.setVisibility(View.VISIBLE);
            }
        }
        chooiseCompany.setOnClickListener(new View.OnClickListener() {//选择集团監聽
            @Override
            public void onClick(View view) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    mClubPopWindow.showAsDropDown(chooiseCompany, 0, 0, CENTER);
                    // 设置背景颜色变暗
                    WindowManager.LayoutParams lp = mActivity.getWindow().getAttributes();
                    lp.alpha = 0.5f;
                    mActivity.getWindow().setAttributes(lp);
                } else {
                    mClubPopWindow.showAsDropDown(chooiseCompany, 0, 0);
                    // 设置背景颜色变暗
                    WindowManager.LayoutParams lp = mActivity.getWindow().getAttributes();
                    lp.alpha = 0.5f;
                    mActivity.getWindow().setAttributes(lp);
                }
            }
        });
        chooiseTime.setOnClickListener(new View.OnClickListener() {//选择年月監聽
            @Override
            public void onClick(View view) {
                chooisTime();
            }
        });
//            btn_chooise_currency.setText();
        totalMoney.setText(accountListBean.getCommonValueSum() + "萬");//设置总金额
        hideProgressDialog();
    }

    /**
     * 查詢币种成功回調
     *
     * @param currencyListBean
     */
    @Override
    public void showqueryCurrencyList(final CurrencyListBean currencyListBean) {

        if (currencyListBean != null && currencyListBean.getCurrencys().size() > 0) {
//            roomId = Integer.parseInt(currencyListBean.getCurrencys().get(0).getRoomid());
            //填充廳數據
            //初始化一个空list的adapter，网络错误时使用，第一次加载到数据时重新初始化adapter并绑定recycleview

            popAdapter = new PopAdapter(R.layout.pop_list_item, currencyListBean);
            clubrecyclerView.setAdapter(popAdapter);
            clubrecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
//           clubrecyclerView.seton
            //集團點擊監聽
            popAdapter.setOnCliCkItemListenerr(new PopAdapter.OnCliCkItemListener() {
                @Override
                public void clickItem(int position) {
                    chooiseCompany.setText(currencyListBean.getCurrencys().get(position).getCurrencyName1());//動態改變集團名稱
                    tvCurrencyType.setText(currencyListBean.getCurrencys().get(position).getCurrencyName1());//动态改变币种类型

                    //  roomname = currencyListBean.getCurrencys().get(position).getCurrencyName1();
                    //查詢最大日期
//                    if (position != 0) {
//                        mPresenter.queryMaxChangemonth(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().getServerProject(), queryRegisBean.getServerSetting().getServerPort(), roomId);
//                    } else {
                    if (roommonth.equals("全年")) {
                        mPresenter.queryClientReserved02(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().getServerProject(), queryRegisBean.getServerSetting().getServerPort(),
                                clientindex, roomyear + "", "", "0", "0",chooiseCompany.getText().toString());
                    } else {
                        mPresenter.queryClientReserved02(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().getServerProject(), queryRegisBean.getServerSetting().getServerPort(),
                                clientindex, roomyear + "", roommonth + "", "0", "0",chooiseCompany.getText().toString());
                    }
//                    }

                    mClubPopWindow.dissmiss();
                }
            });
            //填充廳數據
            mallRoomListBean = currencyListBean;
//            roomId = allRoomListBean.getRoomList().get(0).getRoomid();//默认第一个厅
//            //查询子户口
            if (queryRegisBean != null && !queryRegisBean.getServerSetting().getServerAddress().equals("")) {
                //查询子户口
                showProgressDialog("请稍等...");
                mPresenter.queryClientReserved02(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().getServerProject(), queryRegisBean.getServerSetting().getServerPort(),
                        clientindex, roomyear + "", roommonth + "", "0", "0",chooiseCompany.getText().toString());
            }
        }
//    }
    }

//    //查询最大日期
//    @Override
//    public void showMaxChangemonthList(MaxChangemonthBean maxChangemonthBean) {
//        if (maxChangemonthBean != null) {
////            vipUserInfornationAdapter.removeAllHeaderView();
//            roomyear = maxChangemonthBean.getRoomyear();
//            roommonth = maxChangemonthBean.getRoommonth();
//            mmaxChangemonthBean = maxChangemonthBean;
//            btn_choose_time.setText(maxChangemonthBean.getRoomyear() + "/" + maxChangemonthBean.getRoommonth());//设置日期
////        //查询子户口
//            if (queryRegisBean != null && !queryRegisBean.getServerSetting().getServerAddress().equals("")) {
//                showProgressDialog("请稍等...");
////                vipUserInfornationAdapter.removeAllHeaderView();
//                mPresenter.queryClientReserved02(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().getServerProject(), queryRegisBean.getServerSetting().getServerPort(),
//                        clientindex, roomId, maxChangemonthBean.getRoomyear() + "", maxChangemonthBean.getRoommonth() + "", "0", "0", type);
//            }
//        } else {
//            ToastUtils.showToast("没有日期");
//        }
//    }

    //所有厅网络错误
    @Override
    public void showAllRoomNetworkError(Throwable throwable) {
        ptrClass.refreshComplete();//
        hideProgressDialog();
//        vipUserInfornationAdapter.setEmptyView(errorView);
    }


}
